#-------------------------------------------------------------------------------
# Name:        AnimatedSprite
# Purpose:
#
# Author:      Michael Blackwood
#
# Created:     23/10/2013
# Copyright:   (c) Monxcleyr Productions 2013
# Licence:     GPL v3
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import pygame, logging
import sprite

class AnimatedSprite(sprite.Sprite):


  def __init__(self, objtype, name, attributes, imagehandler):
    sprite.Sprite.__init__(self, objtype, name, attributes, imagehandler)
    self.ancestors.append('animatedsprite')
    temp = []
    for i in range(self.attributes['initialframe'], int(self.attributes['framecount'])):
      temp.append(i)
    self.attributes['animframes'] = temp
    self.attributes['framecount'] = int(self.attributes['framecount'])
    self.attributes['animspeed'] = float(self.attributes['animspeed'])
    self.attributes['cycle'] = self.attributes['cycle'] == 'True'

    self.direction = 0
    self.time = 0


  def update(self, common):
    """ Calls _animupdate so other classes can inherit without having to recode update. """
    self._animupdate(common)


  def _animupdate(self, common):

    """ Sets which sprite frame to draw based on time. """

    framepermilli = self.attributes['animspeed'] / 1000.0

    self.time += common.frametime

    frameindex = int(self.time * framepermilli)

    framecount = self.attributes['framecount']
    animframes = self.attributes['animframes']
    if self.attributes['cycle'] == True:
      framecount = self.attributes['framecount'] + self.attributes['framecount'] - 2
      animtemp = animframes[::-1]
      animframes = self.attributes['animframes'] + animtemp[1:-1]

    if frameindex > len(animframes) - 1:
      frameindex = 0
      self.time = 0

    frame = animframes[frameindex]
    self.attributes['frame'] = frame


